package com.umeox.watch.moto.chat.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.RemoteException
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.moto.watch.themes.widget.TextView
import com.umeox.watch.moto.apiclient.model.GetFriendsAttrDTO
import com.umeox.watch.moto.chat.R
import com.umeox.watch.moto.chat.adapter.FriendSelectListAdapter
import com.umeox.watch.moto.chat.bean.DeviceFriendInfo
import com.umeox.watch.moto.chat.bean.GroupMemberDetail
import com.umeox.watch.moto.chat.db.DBUtils.getContactList
import com.umeox.watch.moto.dataservice.DataProvider
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AddGroupFriendActivity : ThemeAppCompatActivity(),
    FriendSelectListAdapter.OnItemClickListener {

    companion object {
        fun intoAddGroupFriendActivity(context: Context, groupId: String) {
            context.startActivity(Intent(context, AddGroupFriendActivity::class.java).apply {
                putExtra("groupId", groupId)
            })
        }
    }

    private lateinit var ivAdd: TextView
    private lateinit var contactList: RecyclerView
    private val adapter = FriendSelectListAdapter()
    private var isCreating = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_group_friend)

        val groupId = intent?.getStringExtra("groupId")!!

        ivAdd = findViewById(R.id.iv_add)
        contactList = findViewById(R.id.contactList)
        contactList.adapter = adapter
        adapter.setOnItemClickListener(this)
        ivAdd.setOnClickListener {
            if (isCreating) {
                return@setOnClickListener
            }
            isCreating = true
            addGroupFriends(groupId)
        }
        getData(groupId)
    }

    private fun addGroupFriends(groupId: String) {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val friendIds = adapter.getSelectedFriendIds()
                addGroupFriends(groupId, friendIds)
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                finish()
            }
        }
    }

    private fun getData(groupId: String) {
        lifecycleScope.launch(Dispatchers.IO) {
            val list = getDeviceFriendsList(groupId)
            withContext(Dispatchers.Main) {
                adapter.setData(list)
            }
        }
    }

    private fun getDeviceFriendsList(groupId: String): List<DeviceFriendInfo> {
        //获取好友群聊配置列表
        val friendsAttrList = try {
            getFriendsAttr().records
        } catch (e: Exception) {
            listOf()
        }

        //获取群成员列表
        val groupMemberList = getGroupMemberList(groupId)

        //获取设备好友列表
        val deviceFriendList = getContactList().filter {
            it.type == 2 && !it.isGroup
        }

        val deviceFriendInfoList = mutableListOf<DeviceFriendInfo>()
        //生成显示列表
        for (contactInfo in deviceFriendList) {
            var available = false
            for (deviceFriendAttrDTO in friendsAttrList) {
                if (deviceFriendAttrDTO.friendId == contactInfo.friendId) {
                    available = (deviceFriendAttrDTO.customGroup == 1)
                }
            }
            if (available) {
                for (member in groupMemberList) {
                    if (member.memberId == contactInfo.friendId) {
                        available = false
                    }
                }
            }

            val deviceFriendInfo = DeviceFriendInfo(contactInfo, available, available)
            deviceFriendInfoList.add(deviceFriendInfo)
        }

        return deviceFriendInfoList
    }

    private fun getGroupMemberList(groupId: String): List<GroupMemberDetail> {
        val list = mutableListOf<GroupMemberDetail>()
        val memberList = DataProvider.getIMGroupMembersByGroupId(groupId)
        if (!memberList.isNullOrEmpty()) {
            for (temp in memberList) {
                val task: GroupMemberDetail? = GroupMemberDetail.convertFromValues(temp)
                if (task != null) {
                    list.add(task)
                }
            }
        }
        return list
    }

    @Throws(RemoteException::class)
    fun getFriendsAttr(): GetFriendsAttrDTO {
        return PushApiClientProxy.fetchBinder().getFriendsAttr()
    }

    @Throws(RemoteException::class)
    fun addGroupFriends(groupId: String, friendIds: List<String>) {
        PushApiClientProxy.fetchBinder().inviteJoinGroup(groupId, friendIds)
    }


    @SuppressLint("NotifyDataSetChanged")
    override fun onItemClick(position: Int, data: DeviceFriendInfo) {
        data.selected = !data.selected
        adapter.notifyItemChanged(position)
    }
}